/*
 * system_timer.c
 *
 */
#ifdef __unix__
# include <unistd.h>
#elif defined _WIN32
# include <windows.h>
#define sleep(x) Sleep(1000 * x)
#endif

#include <stdio.h>
#include <unistd.h>

#include "../CPU/cpu.h"
#include "../CPU/interrupt.h"
#include "system_timer.h"

void system_timer_init(system_timer* st, int interval_length, cpu* proc){
	st->interval_length = interval_length;
	interrupt intr;
	//printf("SYSTEM TIMER: initialized\n");
	// Initialize an Interrupt to be used by the System Timer.
	// Interrupt has "System Timer" name as well as No Data and a Type of 2
	char *process_name = "System Timer";
	char *data = "";
	interrupt_init(&intr, 2, process_name, data, NULL);
	st->intr = intr;
	st->my_st_cpu = proc;
}

void system_timer_run(system_timer* st){
	// While Loop to Sleep for the defined interval length... (forever...)
	while(1){
		//printf("SYSTEM TIMER: Sleeping %d Seconds\n", interval_length);
		sleep(st->interval_length);
		// Enqueue the Interrupt into the CPU then Resume Sleeping
		//printf("SYSTEM TIMER: Done Sleeping Enqueing Interrupt\n");
		enqueue_interrupt(st->my_st_cpu, &(st->intr));
	}
}
